package cn.mrlong.tools.note

import cn.mrlong.tools.bean.Note
import cn.mrlong.tools.bean.NoteDaoImpl
import cn.mrlong.tools.constant.PluginConstant
import cn.mrlong.tools.service.DatabaseBasicService
import cn.mrlong.tools.util.MessageUtil
import cn.mrlong.tools.util.OpenHtmlFileInBrowser
import cn.mrlong.tools.util.ScreenSizeUtil
import cn.mrlong.tools.util.TimeUtil
import cn.mrlong.tools.view.LineNumberHeaderView
import cn.mrlong.tools.view.setLineNumberView
import com.intellij.openapi.wm.ToolWindow
import com.intellij.ui.util.maximumWidth
import org.apache.http.util.TextUtils
import java.awt.*
import java.awt.event.MouseEvent
import javax.swing.*
import javax.swing.event.MouseInputListener
import javax.swing.table.DefaultTableCellRenderer
import javax.swing.table.DefaultTableModel


class NoteWindow(toolWindow: ToolWindow?) {
    var rootJaTablePanel: JTabbedPane? = null;
    var findtable: JTable? = null
        set(value) {
            field = value
            field?.setRowHeight(200)
        }

    var n_root: JPanel? = null
    var findPanel: JPanel? = null
    var addPanel: JPanel? = null

    var addButton: JButton? = null
    var clearButton: JButton? = null
    var convertBtn: JButton? = null
    var find: JButton? = null
    var open_perfetto: JButton? = null
    var open_winscope: JButton? = null

    private var title: JTextField? = null
    private var keywords: JTextField? = null
    private var findtext: JTextField? = null
    private var timebefore: JTextField? = null
    private var timeafter: JTextField? = null

    private var textArea: JTextArea? = null
    private var textAreaPane: JScrollPane? = null
    private var findtextinfoPane: JScrollPane? = null
    private var findtextinfo: JTextArea? = null
        set(value) {
            field = value
            val width = ScreenSizeUtil.screen.width
            field?.setCaretPosition(0);
            field?.setSize(width / 2, findtext?.height ?: -1)
            field?.maximumWidth = width / 2
        }

    init {
        open_perfetto?.addActionListener {
            OpenHtmlFileInBrowser.openUrl(OpenHtmlFileInBrowser.PERFETTO_URL)
        }
        open_winscope?.addActionListener {
            OpenHtmlFileInBrowser.openFileOrUrl(
                "" + PluginConstant.TEMP_IMAGE_DIRECTORY_PATH.toAbsolutePath().toString() + "/cn/mrlong/tools/util/winscope.html"
            )
        }
        clearButton?.addActionListener {
            clearText()
        }
        addButton?.addActionListener {
            saveText()
        }
        find?.addActionListener {
            findTextAction()
        }
        findtextinfoPane?.apply {
            setLineNumberView(findtextinfo!!)
        }
        textAreaPane?.apply {
            setLineNumberView(textArea!!)
        }
        findtable?.apply {
            setRowHeight(35)
            //border = BorderFactory.createEtchedBorder()
            addMouseListener(object : MouseInputListener {
                override fun mouseClicked(e: MouseEvent?) {
                    if (e!!.clickCount === 1) { // 单击事件
                        val count = findtable?.selectedRow ?: 0
                        findtextinfo?.text = findtable?.model?.getValueAt(count, 3).toString()
                    } else if (e!!.clickCount === 2) { // 单击事件
                        rootJaTablePanel?.selectedIndex = 0
                        val count = findtable?.selectedRow ?: 0
                        note.id = findtable?.model?.getValueAt(count, 0).toString().toInt()
                        title?.text = findtable?.model?.getValueAt(count, 1).toString()
                        keywords?.text = findtable?.model?.getValueAt(count, 2).toString()
                        textArea?.text = findtable?.model?.getValueAt(count, 3).toString()
                        addButton?.text = "update"
                    }
                }

                override fun mousePressed(e: MouseEvent?) {
                }

                override fun mouseReleased(e: MouseEvent?) {
                }

                override fun mouseEntered(e: MouseEvent?) {
                }

                override fun mouseExited(e: MouseEvent?) {
                }

                override fun mouseDragged(e: MouseEvent?) {
                }

                override fun mouseMoved(e: MouseEvent?) {
                }

            })
        }
        convertBtn?.addActionListener {
            timeafter?.text = TimeUtil.convert(timebefore?.text)
        }
    }

    private fun findTextAction() {
        var findKey = findtext?.text
        var datas = if (TextUtils.isEmpty(findKey)) {
            NoteDaoImpl.instance?.findAll(DatabaseBasicService().connection)
        } else {
            NoteDaoImpl.instance?.findAllByKeyWords(DatabaseBasicService().connection, findKey)
        }
        if (!datas.isNullOrEmpty()) {
            val model = object : DefaultTableModel() {
                override fun isCellEditable(row: Int, column: Int): Boolean {
                    return false
                }
            }

            model.addColumn("id")
            model.addColumn("title")
            model.addColumn("keyword")
            model.addColumn("content")

            datas.forEach {
                it?.let {
                    model.addRow(
                        arrayOf<Any>(
                            it.id.toString(),
                            it.title.toString(),
                            it.type.toString(),
                            it.content.toString()
                        )
                    )
                }
            }
            findtable?.model = model
            findtable?.columnModel?.getColumn(0)?.maxWidth = 40
            findtable?.columnModel?.getColumn(1)?.maxWidth = 100
            findtable?.columnModel?.getColumn(2)?.maxWidth = 200
            findtable?.columnModel?.getColumn(3)?.preferredWidth = 260
            findtable?.autoResizeMode = JTable.AUTO_RESIZE_ALL_COLUMNS;
            findtable?.invalidate()
        }
    }

    var note = Note()
    private fun saveText() {
        note.title = title?.text
        note.content = textArea?.text
        note.type = keywords?.text
        if (TextUtils.isEmpty(note.title)) {
            MessageUtil.show("Title is Null")
            return
        }
        if (TextUtils.isEmpty(note.type)) {
            MessageUtil.show("KeyWords is Null")
            return
        }
        if (note.id == -1) {
            NoteDaoImpl().insert(DatabaseBasicService().connection, note)
            MessageUtil.show("Save success")
        } else {
            note.updateTime = System.currentTimeMillis()
            NoteDaoImpl().update(DatabaseBasicService().connection, note)
            MessageUtil.show("Update success")
        }
        clearText()
    }

    private fun clearText() {
        addButton?.text = "add"
        note.id = -1
        title?.text = ""
        keywords?.text = ""
        textArea?.text = ""
    }

    val content: JComponent?
        get() = n_root
}
